/**
 * UltraCSA平台系统文件
 * 
 * Copyright 2016 北京神州泰岳软件股份有限公司
 */
package com.ultrapower.ultracsa.product.restful;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContext;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ultrapower.ultracsa.product.conf.ProjectConfigServer;
import com.ultrapower.ultracsa.product.conf.ProjectPathCfg;
import com.ultrapower.ultracsa.product.dao.KickstartDao;
import com.ultrapower.ultracsa.product.dao.ModelDao;
import com.ultrapower.ultracsa.product.pojo.KickStart;
import com.ultrapower.ultracsa.product.pojo.Server;
import com.ultrapower.ultracsa.product.pojo.ShellFile;
import com.ultrapower.ultracsa.product.pojo.Task;
import com.ultrapower.ultracsa.product.service.impl.OSDeployImpl;
import com.ultrapower.ultracsa.product.util.BeanUtil;
import com.ultrapower.ultracsa.product.util.MD5Util;
import com.ultrapower.ultracsa.product.util.thread.ThreadPool;

/**
 * 作者: xtxb
 * 
 * 日期: 2016
 * 
 * 版权说明：北京神州泰岳软件股份有限公司
 * 
 * TODO 源码说明
 */
@RestController
public class  OSServerAPI {
	private static Logger log=Logger.getLogger(OSServerAPI.class);
//	@RequestMapping(value = "/V/1/user/", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
//	public ResponseEntity<List<User>> getUser(){
//		List<User> list=new ArrayList();
//		list.add(new User(1,"asdfsdaf"));
//		list.add(new User(2,"ggg"));
//		return new ResponseEntity<List<User>>(list,HttpStatus.OK);	
//	}
//	
//	@RequestMapping(value = "/V/1/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
//        System.out.println("Fetching User with id " + id);
//        return new ResponseEntity<User>(new User(id,""+System.currentTimeMillis()), HttpStatus.OK);
//    }
	
	/**
	 * 用于向系统中注册ISO镜像库或软件库，当系统中存在对应的Server时，更新其状态为：已连接
	 * @param type 1-ISO镜像库  2-软件库
	 * @param ip
	 * @param port
	 * @return
	 */
	@RequestMapping(value="/V/1/server/{type:[1-2]}/{ip}/{port}", method=RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
	public ResponseEntity<Map<String,String>> registerServer(@PathVariable("type") int type,@PathVariable("ip") String ip,@PathVariable("port") int port){
		Map result =new HashMap();
		ModelDao dao=BeanUtil.getBean(ModelDao.class);
		Server server=new Server();
		server.setIp(ip);
		server.setServerType(type-1);
		server=dao.getServerByIP(server);
		String uri="http://"+ip+":"+port+"/csaAgent";
		String repo=(type==1?"镜像库":"软件库");
		if(server==null){
			log.info("Server: type="+repo+"; IP="+ip);
			server=new Server();
			server.setIp(ip);
			server.setServerType(type-1);
			server.setServerUrl(uri);
			server.setServerStatusMark("0");
			server.setUpdateTime(new Date());
			dao.insertServer(server);
			log.info("注册Server成功！Server="+server );
			result.put("success", repo+"注册成功!");
			return new ResponseEntity<Map<String,String>>(result, HttpStatus.OK);
		}else{
			server.setServerStatusMark("0");
			server.setUpdateTime(new Date());
			dao.updateServer(server);
			result.put("success","更新"+repo+"状态成功!");
			return new ResponseEntity<Map<String,String>>(result, HttpStatus.OK);
		}
	}
	
	/**
	 * 周期更新task任务状态的api
	 * @param tid   Task任务的id，
	 * @param status  任务状态  1-处理中 2-处理成功 3-处理失败
	 * @param isEnd   Task任务是否已经结束 1--未结束  2--结束
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/V/1/task/{tid}/{status:[1-3]}/{isEnd:[1-2]}",method=RequestMethod.PUT,produces={"application/json;charset=UTF-8"})
	public ResponseEntity<Map<String,String>> updateTaskStatus(@PathVariable("tid") int tid,@PathVariable("status") int status, @PathVariable("isEnd") int isEnd,HttpServletRequest request){
		Map result =new HashMap();
		ModelDao dao=BeanUtil.getBean(ModelDao.class);
		try{
		Task task=dao.getTaskByID(tid);
		System.out.println("sfdsf======================sdf");
		if(task==null){
			result.put("error","任务不存在");
		    return new ResponseEntity<Map<String,String>>(result, HttpStatus.NOT_FOUND);
		}
		task.setTaskStatus(status-1);
		if(request.getParameter("taskMsg")!=null)
			task.setTaskMsg(request.getParameter("taskMsg"));
		if(isEnd==2){
			task.setEndTime(new Date());
		}
		dao.updateTask(task);
		}catch(Exception e){
			e.printStackTrace();
		}
		result.put("success","状态更新成功");
		return new ResponseEntity<Map<String,String>>(result, HttpStatus.OK);
	}
	
	/**
	 * 用于保存安装日志
	 * @param ip
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/V/1/log/{ip}",method=RequestMethod.POST, produces = {"application/text;charset=UTF-8"} )
	public ResponseEntity<Boolean> uploadLog(@PathVariable("ip") String ip,HttpServletRequest request){
		Map result =new HashMap();
		String filePath=ProjectPathCfg.getProjectHomePath()+File.separator+"webapps"+File.separator+"csa"+File.separator+"WEB-INF"+File.separator+"file"+File.separator+"log"+File.separator;
		BufferedReader br=null;
		BufferedWriter bw=null;
		try {
			br=new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
			bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath+ip+".log"),"UTF-8"));
			String line=null;
			while((line=br.readLine())!=null)
				bw.write(line+"\n");
			return new ResponseEntity<Boolean>(true, HttpStatus.OK);
		} catch (IOException e) {
			log.error("",e);
			return new ResponseEntity<Boolean>(false, HttpStatus.OK);
		}finally{
			try {
				br.close();
			} catch (IOException e) {
				log.error("",e);
			}
			try {
				bw.close();
			} catch (IOException e) {
				log.error("",e);
			}
		}
	}
	
	/**
	 * 获取Web服务中的所有KS文件数据,请求中包含md5信息，用于增量获取KS文件
	 * @return
	 */
	@RequestMapping(value="/V/1/kickstarts/differ",method=RequestMethod.GET,produces={"application/json;charset=UTF-8"} )
	public ResponseEntity<Object> getKickstartMeta( HttpServletRequest request){
		List<KickStart> list=BeanUtil.getBean(OSDeployImpl.class).kickStartList();
		if(list==null){
			Map str =new HashMap();
			str.put("errorMsg", "系统中不存在KS文件");
			return new ResponseEntity<Object>(str, HttpStatus.NO_CONTENT);
		}
		//获取客户端查询KS是提交的ksMD5信息
		String kslist=request.getHeader("ksList");
		Map<String,String> ksMap=null;
		if(kslist==null)
			ksMap=new HashMap();
		else{
			ObjectMapper objectMapper = new ObjectMapper();
			try {
				JsonNode node=objectMapper.readTree(kslist);
				ksMap=objectMapper.convertValue(node, Map.class);
			}catch (Exception e) {
				log.error("", e);
			}
		}
		List<Map<String,String>> result=new ArrayList();
		Map<String,String> map=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String ksfilePath=ProjectPathCfg.getProjectHomePath()+File.separator+"webapps"+File.separator+"csa"+File.separator+"WEB-INF"+File.separator+"file"+File.separator+"kickstart"+File.separator;
		String shfilePath=ProjectPathCfg.getProjectHomePath()+File.separator+"webapps"+File.separator+"csa"+File.separator+"WEB-INF"+File.separator+"file"+File.separator+"script"+File.separator;
		Properties pro=new Properties();
		BufferedReader in=null;
		try{
			for (KickStart sk : list) {
				Map str =new HashMap();
				String timeSum="";
				String ksName=sk.getUserAccount()+sdf.format(sk.getCreateTime());
				File file=new File(ksfilePath+ksName+".properties");
				if(!file.exists()){
					str.put("errorMsg", "kickstart文件："+ksName+" 不存在");
					return new ResponseEntity<Object>(str, HttpStatus.NO_CONTENT);
				}
				timeSum+=sk.getUpdateTime().getTime()+"-";
				in=new BufferedReader(new FileReader(file));
				pro.load(in);
				map=new HashMap(pro);
				in.close();

				map.put("ksName", ksName);
				map.put("osName", sk.getIso().getIsoName());
				map.put("ksType", sk.getIso().getIsoType());
				List<ShellFile> slist=BeanUtil.getBean(KickstartDao.class).getShellByKicstartId(sk.getCsaId());
				StringBuffer sb=new StringBuffer("");
				if(slist!=null){
					for(ShellFile shell: slist){
						file=new File(shfilePath+shell.getFileName());
						if(!file.exists()){
							str.put("errorMsg", "kickstart文件关联的脚本文件："+shell.getFileName()+" 不存在");
							return new ResponseEntity<Object>(str, HttpStatus.NO_CONTENT);
						}
						timeSum+=shell.getUpdateTime().getTime()+"-";
						in=new BufferedReader(new FileReader(file));
						String line=null;
						while((line=in.readLine())!=null){
							sb.append(line+"\n");
						}
						in.close();
						sb.append("\n\n");
					}
				}
				String md5=MD5Util.getMD5(timeSum);
				if(!ksMap.containsKey(ksName) || !ksMap.get(ksName).equals(md5)){
					map.put("shellFile",sb.toString());
					map.put("md5",md5);
					result.add(map);
				}
			}	
			return new ResponseEntity<Object>(result, HttpStatus.OK);
		}catch(Exception e){
			log.error("", e);
			Map str =new HashMap();
			str.put("taskMsg", e.getMessage());
			return new ResponseEntity<Object>(str, HttpStatus.NO_CONTENT);
		}
	}
	
	/**
	 * 获取Web服务中的所有KS文件数据
	 * @return
	 */
	@RequestMapping(value="/V/1/install/status",method=RequestMethod.POST )
	public void updateInstallStatus( HttpServletRequest request){
		String ip=request.getParameter("ip");
		String percent=request.getParameter("percent");
		String msg=request.getParameter("msg");

		String key=ProjectConfigServer.getConfig("install",percent);
		if(key==null)
			msg="安装中";
		else{
			msg=new RequestContext(request).getMessage(key);
			if(msg==null)
				msg="安装中";
		}
		System.out.println(ip+"==="+msg+"==="+percent);
		if(ip==null)
			 return;
		try {
			ThreadPool .execTask("INSTALL_TASK", new IntallStatus(ip,percent,msg));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
